/** SessionManager */
package server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;

/**
 * SessionManager manages currently connected SESSIONs in a thread-safe manner.
 * @author jessienewman
 * @version $Revision: 1.0 $
 */
public class SessionManager {
	
	/**
	 * Field LOGGER.
	 */
	private static final Logger LOGGER = Logger.getLogger(SessionManager.class.getName());
	
	/**
	 * Field SESSIONs.
	 */
	private static Map<Integer,Integer> SESSIONs = new HashMap<Integer, Integer>();
	
	/**
	 * Adds a SESSION to the SESSION table.
	 * @param userId the id of the SESSION's user
	 * @return Integer the SESSION ID * 
	 * @throws IOException if there are too many SESSIONs */
	public static synchronized Integer addSession(
			final Integer userId) throws IOException {
		if (SESSIONs.keySet().size() >= 5) { // $codepro.audit.disable numericLiterals
			throw new IOException("Sessions full!"); // $codepro.audit.disable nullPointerDereference
		}
		Integer sessionId = null;
		Random rand = new Random();
		
		while (sessionId == null || SESSIONs.get(sessionId) != null) {
			sessionId = userId * rand.nextInt(100); // $codepro.audit.disable numericLiterals
		}
		
		LOGGER.info("Session started for userId: " + userId + " SESSIONId: " + sessionId);
		SESSIONs.put(sessionId, userId);
		return sessionId;
	}
	
	/**
	 * Removes a SESSION from the SESSION table.
	 * @param sessionId the currently open SESSION's id
	 */
	public static synchronized void removeSession(final Integer sessionId) {
		Integer userId = SESSIONs.remove(sessionId);
		if (userId != null) {
			LOGGER.info("Removed SESSION for SESSIONId: " + sessionId);
		} else {
			LOGGER.warning("Cannot remove SESSION: Session id " + 
					sessionId + " does not exist!");
		}
	}
	
	/**
	 * Returns the user id associated with the given SESSION id.
	 * @param sessionId the SESSION's id
	
	 * @return the associated user id */
	public static synchronized Integer getUserId(final Integer sessionId) {
		Integer userId = SESSIONs.get(sessionId);
		
		if (userId == null) {
			LOGGER.warning("Cannot retrieve SESSION: Session id " + 
					sessionId + " does not exist!");
		}
		
		return userId;
	}

	/**
	 * super's toString
	
	 * @return super's toString */
	public String toString() {
		return super.toString();
	}
}
